package com.baiyang.server.service.article.impl;


import com.alibaba.fastjson.JSONObject;
import com.baiyang.server.control.WebSocketController;
import com.baiyang.server.dao.article.ArticleReadNumDao;
import com.baiyang.server.model.article.Article;
import com.baiyang.server.model.article.ArticleReadNum;
import com.baiyang.server.service.article.ArticleReadNumService;
import com.baiyang.server.service.article.ArticleService;
import com.baiyang.server.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baiyang.server.dao.article.ArticleStateDao;
import com.baiyang.server.model.article.ArticleState;
import com.baiyang.server.service.article.ArticleStateService;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

/**
 * 
 * @author XVX
 * BY: @Primary 注解帮助生命@Autowired优先注入的实列
 */
@Service	
public class ArticleStateServiceImpl extends BaseServiceImpl<ArticleStateDao, ArticleState> implements ArticleStateService{

    @Autowired
    private ArticleStateDao articleStateDao;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleReadNumService articleReadNumService;


    /**
     * 审批
     * @apiNote 1.审批不通过或者需修改时，直接将状态写入数据库，并修改文章表中的状态字段
     *          2.审批通过时：
     *              a.审批结果写入数据库
     *              b.修改文章状态
     *              c.插入文章阅读数量信息
     * @param articleState
     */
    @Override
    @Transactional
    public void approval(ArticleState articleState) {
        // 将数据插入数据库
        articleStateDao.insert(articleState);
        // 修改文章状态
        Article article = new Article();
        article.setId(articleState.getArticleId());
        article.setState(articleState.getState());
        articleService.updateById(article);
        // 通过时创建记录阅读记录信息
        switch (articleState.getState()){
            case ArticleState.PASS:
            {
                ArticleReadNum articleReadNum = new ArticleReadNum();
                articleReadNum.setArticleId(articleState.getArticleId());
                articleReadNum.setNum(0);
                articleReadNumService.insert(articleReadNum);
                // 主推信息给客户端
                article = articleService.selectOne(article);
                sendBySocket(article);
                break;
            }
        };
    }

    /**
     * 主推信息给客户端
     * @param article
     */
    private void sendBySocket(Article article){
        try {
            WebSocketController.sendMessage(JSONObject.toJSONString(article));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
